package com.ruoyi.employee.service.impl;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TokenUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.employee.domain.EmployeeUser;
import com.ruoyi.employee.mapper.EmployeeUserMapper;
import com.ruoyi.employee.service.IEmployeeInfoService;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 店员 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class EmployeeInfoServiceImpl implements IEmployeeInfoService
{
    // 是否允许账户多终端同时登录（true允许 false不允许）
    @Value("${token.soloLogin}")
    private boolean soloLogin;

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    @Autowired
    protected Validator validator;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private EmployeeUserMapper employeeUserMapper;

    @Override
    public AjaxResult loginByPassword(String userName, String password) {
        JSONObject response = new JSONObject();
        // 参数校验
        if(StringUtils.isBlank(userName)){
            return AjaxResult.error("手机号不能为空");
        }
        if(StringUtils.isBlank(password)){
            return AjaxResult.error("密码不能为空");
        }
        EmployeeUser employeeUser = employeeUserMapper.checkUserNameUnique(userName);
        if(StringUtils.isNull(employeeUser)){
            return AjaxResult.error("登录失败：账户不存在");
        }
        if(SecurityUtils.matchesPassword(password, employeeUser.getPassword())){
            return AjaxResult.error("登录失败：账户密码错误");
        }

        employeeUser.setLoginDate(new Date());
        employeeUserMapper.updateUser(employeeUser);

        // 用户验证
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(employeeUser.getUserId());
        loginUser.setUserName(userName);
        loginUser.setNickName(loginUser.getNickName());
        if (!soloLogin)
        {
            // 如果用户不允许多终端同时登录，清除缓存信息
            String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUserId();
            String userKey = redisCache.getCacheObject(userIdKey);
            if (StringUtils.isNotEmpty(userKey))
            {
                redisCache.deleteObject(userIdKey);
                redisCache.deleteObject(userKey);
            }
        }
        String token = createToken(loginUser);
        response.put("token", token);
        // token存redis
        redisCache.setCacheObject(getTokenKey(loginUser.getToken()), loginUser, expireTime, TimeUnit.MINUTES);
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        // 登录成功
        return ajax;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    @Override
    public AjaxResult getLoginUser(HttpServletRequest request) {
        Long userId = SecurityUtils.getUserId();
        EmployeeUser employeeUser = employeeUserMapper.selectUserById(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", employeeUser);
        return ajax;
    }

    @Override
    public AjaxResult logout(HttpServletRequest request) {
        try {
            // 获取请求携带的令牌
            String token = getToken(request);
            Claims claims = TokenUtils.parseToken(token, secret);
            redisCache.deleteObject(getTokenKey(token) + claims.get(Constants.LOGIN_USER_KEY, String.class));
            return AjaxResult.success("登出成功！", null);
        }  catch (Exception ex){
            ex.printStackTrace();
            return AjaxResult.error(ex.getMessage());
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        setUserAgent(loginUser);
        refreshToken(loginUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return TokenUtils.createToken(claims,secret);
    }
    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());
        redisCache.expire(userKey, expireTime, TimeUnit.MINUTES);

        if (!soloLogin)
        {
            // 缓存用户唯一标识，防止同一帐号，同时登录
            String userIdKey = "";
            if(StringUtils.isNotNull(loginUser.getUserId())){
                // 缓存用户唯一标识，防止同一帐号，同时登录
                userIdKey = getUserIdKey(loginUser.getUserId());
            }
            redisCache.setCacheObject(userIdKey, userKey, expireTime, TimeUnit.MINUTES);
        }
    }

    /**
     * 设置用户代理信息
     *
     * @param loginUser 登录信息
     */
    public void setUserAgent(LoginUser loginUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr();
        loginUser.setIpaddr(ip);
        loginUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        loginUser.setBrowser(userAgent.getBrowser().getName());
        loginUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    private String getUserIdKey(Long userId)
    {
        return Constants.LOGIN_USERID_KEY + userId;
    }
}
